package com.yimixian.app.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.squareup.picasso.Picasso;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.PlusMinusIconMessage;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.BaseNaviFragmentGroupActivity;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.adapter.SessionAdapter;
import com.yimixian.app.adapter.SessionRecyclerViewAdapter;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.cart.GoodsItemPresenter;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.goods.GoodDetailActivity;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.CartUpdate;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.KV;
import com.yimixian.app.model.SessionDataBean;
import com.yimixian.app.rest.api.CartUpdateAPI;
import com.yimixian.app.rest.api.SessionDataAPI;
import com.yimixian.app.ui.LoadingPage;
import com.yimixian.app.ui.ParabolaView;
import com.yimixian.app.util.PaoWuXianAnimTool;
import com.yimixian.app.util.PaoWuXianAnimator;
import com.yimixian.app.util.ServiceUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.ymx.sdk.util.DensityUtils;
import com.ymx.sdk.util.DeviceUtils;
import com.ymx.sdk.widget.ListViewLoadMore.AutoPullToRefreshListView;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshBase;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshListView;
import com.ymx.sdk.widget.PullToRefreshView.PullToRefreshRecyclerView;
import com.ymx.sdk.widget.recyclerview.ListRecyclerAdapter;
import com.ymx.sdk.widget.recyclerview.adapterItemAnimator.SlideInBottomAnimationAdapter;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import retrofit.client.Response;

public class SessionActivityListFragment extends BaseFragment implements
		PullToRefreshBase.OnRefreshListener2, ServiceUtils.CountDownDataListener,
		GoodsItemPresenter.OnPlusButtonClickListener, ListRecyclerAdapter.OnItemClickListener {

	public LoadingPage.LoadResult result = LoadingPage.LoadResult.EMPTY;
	private static final String TAG = "SessionActivityListFragment";
	private static final int SESSION_FOR_DETAIL = 1000;
	SessionAdapter mSessionAdapter;
//	SlideInBottomAnimationAdapter adapter;
	ImageView headImage;
	View headView;
	PullToRefreshListView mListView;
	FrameLayout mMainFrame;
	View footerView;
	ArrayList<GoodsItem> mList = new ArrayList<>();

	public long startTime;
	public long isNeedRefreshTime = 1000 * 60 * 60;

	Handler mHandler = new Handler();
	private DataManager mDataManager;
	Picasso picasso;
	private SessionDataAPI mSessionDataAPI;
	public SessionDataBean sessionDataBean;//首次加载的数据
	public SessionDataBean dataBean;//当前的数据
	private int index;
	private String id;
	int mScreenWidth;

	private PlusMinusIconMessage mPlusMinusIconMessage;
	private boolean isNeedGetCart = false;

	public SessionActivityListFragment() {
		super();
	}

	public SessionActivityListFragment(BaseNaviFragmentGroupActivity activity,
									   SessionDataBean sessionDataBean, int position,
									   View empty, FrameLayout mMainFrame) {
		super(activity, empty);
		index = position;
		this.mMainFrame = mMainFrame;
		this.sessionDataBean = sessionDataBean;
	}

	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
	}

	@Override
	protected View createLoadedView() {
		View view = View.inflate(mActivity, R.layout.fragment_activity_session, null);
		picasso = Picasso.with(getContext());
		mScreenWidth = DeviceUtils.getScreenWidth(mActivity);
		initView(view);
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		CartManager.getInstance().setSections(mList);
		CartManager.getInstance().setCartQuantityText();
		if (mSessionAdapter != null && mList!= null) mSessionAdapter.setList(mList);
	}

	void initView(View view){
		mListView = (PullToRefreshListView) view.findViewById(R.id.goods_list);
//		mListView.getRefreshableView().addOnScrollListener(new RecyclerView.OnScrollListener() {
//
//			@Override
//			public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//				//0是停止
//				if (newState == 0) adapter.isScrollUp(0);
//				super.onScrollStateChanged(recyclerView, newState);
//			}
//
//			@Override
//			public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
//				adapter.isScrollUp(dy);
//				super.onScrolled(recyclerView, dx, dy);
//			}
//		});
		mSessionAdapter = new SessionAdapter(mActivity, mList, this);
//		adapter = new SlideInBottomAnimationAdapter(mSessionAdapter);
//		adapter.setFirstOnly(false);
//		adapter.setStartPosition(5);
//		adapter.setDuration(500);

		mListView.setAdapter(mSessionAdapter);
		mListView.setOnRefreshListener(this);
		if (footerView == null){
			footerView = new View(mActivity);
			footerView.setEnabled(false);
			footerView.setVisibility(View.INVISIBLE);
			AbsListView.LayoutParams params = new AbsListView.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT, 250);
			footerView.setLayoutParams(params);
			mListView.getRefreshableView().addFooterView(footerView);
		}
		mDataManager = DataManager.getInstance();
		initHeadView();
	}

	View initHeadView(){
		headView = LayoutInflater.from(mActivity).inflate
				(R.layout.session_item_head_view, null);
		AbsListView.LayoutParams headParams = new AbsListView.LayoutParams(
				AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT);
		headView.setLayoutParams(headParams);

		headImage = (ImageView) headView.findViewById(R.id.item_head_image);
		LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT, DensityUtils.dp2px(mActivity, 45));
		headImage.setScaleType(ImageView.ScaleType.FIT_XY);
//		imageParams.bottomMargin = DensityUtils.dp2px(mActivity, 5);
		headImage.setLayoutParams(imageParams);
		headImage.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				if (dataBean != null && dataBean.banners != null &&
						dataBean.banners.size() > 0) {
					Intent intent = new Intent(getContext(), WebViewActivity.class);
					intent.putExtra(WebViewActivity.EXTRA_URL,
							dataBean.banners.get(0).url);
					startActivity(intent);
				}
			}
		});
		return headView;
	}
	@Override
	public void onDestroy() {
		if(mHandler != null) {
			mHandler.removeCallbacksAndMessages(null);
		}
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Override
	public void onDetach() {
		if (mHandler != null) {
			mHandler.removeCallbacksAndMessages(null);
		}
		super.onDetach();
	}

	@Override
	protected void loadMain() {

	}

	@Override
	protected void load() {//请求数据
		if (sessionDataBean == null) return;
		List<KV> list = sessionDataBean.specials;
		if (list != null && list.size() > index){
			id = list.get(index).keyId;
		}
		if (mHandler != null){
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					fetchData(true, SessionDataAPI.SESSIONDATAURL);
				}
			}, 200);
		}
	}
	@Override
	public void onClick(View v) {

	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase refreshView) {
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				if (sessionDataBean == null) return;
				List<KV> list = sessionDataBean.specials;
				if (list != null && list.size() > index) {
					id = list.get(index).keyId;
				}
				fetchData(true, SessionDataAPI.SESSIONDATAURL);
			}
		}, 800);
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase refreshView) {

	}


	@Override
	public void fetchDataFromNetwork(String key) {
		initRequestAPI(key);
		if (mSessionDataAPI != null && key != null &&
				key.equals(SessionDataAPI.SESSIONDATAURL)){
			mSessionDataAPI.getSessionData();
		}
	}

	@Override
	public void initRequestAPI(String requestKeys) {
		if(requestKeys != null && CartUpdateAPI.CART_UPDATE_API.equals(requestKeys) && mCartUpdateAPI == null) {
			initCartUpdateAPI();
		}
		if(requestKeys != null && SessionDataAPI.SESSIONDATAURL.equals(requestKeys)) {
			List<KV> list = sessionDataBean.specials;
			if (list != null && list.size() > index) {
				id = list.get(index).keyId;
			}
			Address address = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
			if (address != null && !StringUtils.isEmpty(address.storeId)){
				mSessionDataAPI = new SessionDataAPI(address.storeId,
						StringUtils.isEmpty(id) ? "" : id, this);
			}
			//			Store store = SharedPreferencesHelper.getStore(SharePreferenceKeys.CURRENT_STORE);
			//			mSessionDataAPI = new SessionDataAPI(store.id, id, this);
		}
	}

	/**
	 * 同步购物车数据
	 */
	private void flushCartData() {
		if(isNeedGetCart && DataManager.getInstance().get(CacheKeys.TOKEN) != null) {
			getCartData();
			isNeedGetCart = false;
		}
	}
	/**
	 * 获取购物车数据
	 */
	private void getCartData() {
		fetchUpdateCartData();
		if(getActivity() != null) {
			showPopupWindow(getActivity(), R.id.popupwindow_container);
		}
		if (mCartUpdateAPI != null) {
			mCartUpdateAPI.getCartInfo();
		}
	}
	@Override
	public void onHttpSuccess(String url, JSONObject responseJson) {
		if (url.contains(SessionDataAPI.SESSIONDATAURL) && responseJson !=null &&
				mSessionDataAPI != null){
			dataBean = mSessionDataAPI.parseJson(responseJson);
			if (dataBean.goods != null && dataBean.goods.size() > 0
					|| (dataBean.banners != null && dataBean.banners.size() > 0)){
				startTime = System.currentTimeMillis();
				mList = dataBean.goods;
				result = LoadingPage.LoadResult.SUCCEED;
			}else{
				result = LoadingPage.LoadResult.EMPTY;
			}

			setLoadResult(result);
			initData(dataBean);
		}

		if (mCartUpdateAPI != null) {
			if(url.contains(mCartUpdateAPI.CART_UPDATE)) {
				CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
				CartManager.getInstance().updateCartGoods(cartUpdate,mPlusMinusIcon);
			}
			if(url.contains(CartUpdateAPI.CART_GET)) {
				CartUpdate cartUpdate = mCartUpdateAPI.parseJson(responseJson);
				CartManager.getInstance().updateCartGoods(cartUpdate);
				if(mSessionAdapter != null) {
					mSessionAdapter.notifyDataSetChanged();
				}
				if(mPlusMinusIconMessage != null && mPlusMinusIconMessage.message.contains("/IsFisrt") && mPlusMinusIconMessage.icon != null ) {
					mPlusMinusIconMessage.message = mPlusMinusIconMessage.icon.mCurrentButtonState;
					EventBus.getDefault().post(mPlusMinusIconMessage);
					EventBus.getDefault().removeStickyEvent(mPlusMinusIconMessage);
				}
			}
			if(mPlusMinusIcon != null) {
				mPlusMinusIcon.setButtonCanClick(true);
			}
			UiUtils.updateCartDescription(getActivity(), Constants.PageType.SESSION);
		}
		hidePopupWindow();
	}

	@Override
	public void getRawResponse(String url, Response response) {
		super.getRawResponse(url, response);
		ServiceUtils.setTime(response);
	}

	void initData(SessionDataBean bean){
		if (headView != null){
			mListView.getRefreshableView().removeHeaderView(headView);
		}
		if (mListView != null) mListView.onRefreshComplete();
		if (result == LoadingPage.LoadResult.SUCCEED){
			if (isNeedGetCart) flushCartData();
			CartManager.getInstance().setSections(mList);
			CartManager.getInstance().setCartQuantityText();
			ServiceUtils.infilterServiceData(getActivity(), mList, Constants.ServicePageType.SESSIONFRAGMENT + index);

			mSessionAdapter.setList(mList);
			if (picasso != null && bean.banners != null && bean.banners.size() > 0){
				if (headView != null && headImage != null){
					picasso.load(mDataManager.getImageUrl(bean.banners.get(0).image,
							DeviceUtils.getScreenWidth(mActivity)))
							.placeholder(R.drawable.placeholder)
							.into(headImage);
					mListView.getRefreshableView().addHeaderView(headView);
//					mSessionAdapter.addHeaderView(headView, 1);
				}
			}
		}
	}

	//是否过时
	public void showIsTime(){
		isNeedUpdate();
		if (System.currentTimeMillis() - startTime > isNeedRefreshTime){
			startTime = System.currentTimeMillis();
			result = LoadingPage.LoadResult.EMPTY;
			setLoadResult(LoadingPage.LoadResult.EMPTY);
			showLoad();
		}
	}

	// 第一次加载，直接显示
	public void show(SessionDataBean sessionDataBean) {
		if (!EventBus.getDefault().isRegistered(this)) {
			EventBus.getDefault().registerSticky(this);
		}
		if (sessionDataBean != null){
			if ((sessionDataBean.goods != null && sessionDataBean.goods.size() > 0)
					|| (sessionDataBean.banners != null && sessionDataBean.banners.size() > 0)){
				startTime = System.currentTimeMillis();
				mList = sessionDataBean.goods;
				result = LoadingPage.LoadResult.SUCCEED;
			}else{
				result = LoadingPage.LoadResult.EMPTY;
			}
			setLoadResult(result);
			initData(sessionDataBean);
			ServiceUtils.infilterServiceData(mActivity, mList, Constants.ServicePageType.SESSIONFRAGMENT + index);
		}else{
			show();
		}
	}
	@Override
	public void OnHttpFailure(String url, String errorMessage, boolean errorFromUs) {
		if (mListView != null) mListView.onRefreshComplete();
		if(mPlusMinusIcon != null) {
			mPlusMinusIcon.setButtonCanClick(true);
		}
		hidePopupWindow();
		//		result = LoadingPage.LoadResult.ERROR;
		//		setLoadResult(result);
	}

	// 发起商品 + / - 的请求
	public void onEventMainThread(PlusMinusIconMessage message) {
		if (message != null) {
			//判断是否为没登陆购买
			if(message.message != null && message.message.contains("/IsFisrt") &&
					message.message.contains(Constants.STATE_SESSIONLIST_BUTTON_BROADCAST)) {
				mPlusMinusIconMessage = message;
				isNeedGetCart = true;
				if (sessionDataBean == null) return;
				List<KV> list = sessionDataBean.specials;
				if (list != null && list.size() > index) {
					id = list.get(index).keyId;
				}
				fetchData(true, SessionDataAPI.SESSIONDATAURL);
				return ;
			}
			//正常购买
			mPlusMinusIcon = message.icon;
			if(message.message != null && message.message.equals(Constants.STATE_SESSIONLIST_BUTTON_BROADCAST)) {
				dealPlusMinusProtocol();
			}
		}
	}

	@Override
	public void onPlusButtonClick(View plusView, Point point, Bitmap animBack) {

		ImageView mCartView = ((YMXMainActivity) getActivity()).getmCartDetailViewHide();
		PaoWuXianAnimTool.startAnim(getActivity(), plusView, mCartView, animBack, PaoWuXianAnimTool.DEFAULT_DURATION, new PaoWuXianAnimator.onPaoWuXianEndListener() {
			@Override
			public void onEnd() {
				if(getActivity() instanceof YMXMainActivity)
					((YMXMainActivity) getActivity()).initCartViewAnim(true);
			}
		});

		if(true)
			return;

		ParabolaView parabolaView = new ParabolaView(getActivity(), animBack);
		if(mMainFrame != null) {
			mMainFrame.addView(parabolaView);
		}
		parabolaView.setAnimListener(new ParabolaView.AnimListener() {
			@Override
			public void onEndAnim() {
				if(getActivity() instanceof YMXMainActivity)
					((YMXMainActivity) getActivity()).initCartViewAnim(true);
			}
		});
		parabolaView.startAnimation(mHandler, SharedPreferencesHelper.getCartViewLocation(), point);
	}

	@Override
	public void OnItemClick(View view, int position) {
		if (mList != null && mList.size() > 0 && position >= 0 && mList.size() > position &&
				!Strings.isNullOrEmpty(mList.get(position).descUrl)) {
			if (mList.get(position).isBuyingGroup == 0) {
				MobclickAgent.onEvent(SystemFramework.getInstance().getGlobalContext(),
						StatConstants.HOME_GOOD_ITEM_IMAGE_CLICK);
				startActivityForResult(GoodDetailActivity.buildIntent(getActivity(),
						String.valueOf(mList.get(position).id)), SESSION_FOR_DETAIL);
			} else {
				startTuanWebActivity(mList.get(position));
			}
		}
	}
	private void startTuanWebActivity(GoodsItem goodsItem) {
		Intent intent = new Intent(getActivity(), WebViewActivity.class);
		intent.putExtra(WebViewActivity.EXTRA_URL, goodsItem.descUrl);
		startActivity(intent);
	}

	@Override
	public void isNeedUpdate() {
		if (mSessionAdapter != null) {
			mSessionAdapter.notifyDataSetChanged();
		}
	}

	@Override
	public void isNeedUnbindService() {

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
	}

}
